package com.sisgesbyte.web.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.sisgesbyte.common.ConstantesInternasSistema;

@WebFilter("/pages/*")
public class LoginFilter implements Filter {
	private FilterConfig config = null;

	public LoginFilter() {

	}

	public void destroy() {
		config.getServletContext().log("Destroying SessionCheckerFilter");
		System.out.println("elimina");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;

		String pageRequest = req.getRequestURL().toString();

		if (req.getSession().getAttribute("usuario") != null
				&& pageRequest.contains("login.xhtml")) {
			res.sendRedirect(ConstantesInternasSistema.PATH_URL_PAGES + "index.xhtml");
		}

		if (req.getSession().getAttribute("usuario") == null
				&& !pageRequest.contains("login.xhtml")) {
			res.sendRedirect(ConstantesInternasSistema.PATH_URL_PAGES + "login.xhtml");

		} else {
			chain.doFilter(request, response);
		}
	}

	public void init(FilterConfig fConfig) throws ServletException {
		this.config = fConfig;
		config.getServletContext().log("Initializing SessionCheckerFilter");
		System.out.println("inicio");
	}

}
